<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
    <!-- 百度禁止转码 -->
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <!-- uc强制竖屏 -->
    <meta name="screen-orientation" content="portrait" />
    <!-- QQ强制竖屏 -->
    <meta name="x5-orientation" content="portrai" />
    <!-- 禁用电话号码邮箱自动识别 -->
    <meta name="format-detection" content="telephone=no,email=no" />
    <title>日期自动算</title>
  </head>

  <body>
    当前：
    <input type="date" name="" id="date" />
    <input type="number" name="" id="number" />天<select name="" id="select"
      ><option value="before">前</option
      ><option value="after">后</option></select
    >的日期
    <div id="computed"></div>
    <script>
      let date = document.getElementById('date')
      var time = new Date()

      date.value = formateDay(time)
      let num = document.getElementById('number')
      let select = document.getElementById('select')
      num.addEventListener('input', computedDay)
      select.addEventListener('change', computedDay)
      date.addEventListener('change', computedDay)
      function formateDay(date) {
        var day = ('0' + date.getDate()).slice(-2)
        var month = ('0' + (date.getMonth() + 1)).slice(-2)
        var today = date.getFullYear() + '-' + month + '-' + day
        return today
      }
      function computedDay() {
        if (!num.value) {
          return
        }
        const a1 = Date.parse(date.value)
        let a2
        if (select.value === 'before') {
          a2 = new Date(a1 - num.value * 1000 * 60 * 60 * 24)
        } else {
          a2 = new Date(a1 + num.value * 1000 * 60 * 60 * 24)
        }
        document.getElementById('computed').innerHTML = formateDay(a2)
      }
    </script>
  </body>
</html>
